import React, { useRef, useState, useEffect } from 'react';
import { history, request } from 'umi';
import '../index.less';
import {
  Button,
  Cascader,
  DatePicker,
  Form,
  Input,
  InputNumber,
  Radio,
  message,
  Upload,
  Card,
} from 'antd';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
const { TextArea } = Input;
export default function Index() {
  // 上传图片  ~~~~~~~vvvvvvv
  const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };
  const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState(); // 图片
  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, (url) => {
        setLoading(false);
        setImageUrl(url);
      });
    }
  };
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        Upload
      </div>
    </div>
  );
  //     ………………^^^上传图片
  const add_juslumn = useRef();
  const onFinish = (values) => {
    console.log('Success:', values);
    request('/api/hyq/addJournalism', {
      method: 'post',
      data: {
        title: values.title,
        publish: timeval,
        content: values.content,
        pictures: imageUrl,
      },
    }).then((res) => {
      alert(res.msg);
    });
  };
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  // 添加状态
  // const { RangePicker } = DatePicker;
  const [timeval, settimeval] = useState(''); // 时间
  const onChange = (value, dateString) => {
    // console.log('Selected Time: ', value);
    // console.log('Formatted Selected Time: ', dateString);
    settimeval(dateString);
  };
  const onOk = (value) => {
    console.log('onOk: ', value);
  };
  // 新增保存
  const Add_juslumn = () => {
    add_juslumn.current.submit();
    // console.log(imageUrl,timeval,'图片，时间')
  };
  return (
    <div className="Main-Text">
      <div className="Main-Header">
        <div className="MeansRightHeadBtn">
          <Button
            onClick={() => {
              Add_juslumn();
            }}
          >
            保存
          </Button>
        </div>
        <div className="MeansRightHeadBtn">
          <Button
            onClick={() => {
              add_juslumn.current.resetFields();
              setImageUrl('');
            }}
          >
            重置
          </Button>
        </div>
        <div className="MeansRightHeadBtn">
          <Button
            onClick={() => {
              history.push('/notice/notice_main');
            }}
          >
            返回
          </Button>
        </div>
      </div>
      <div className="Main-Content">
        <Card>
          <Form
            ref={add_juslumn}
            labelCol={{
              span: 4,
            }}
            wrapperCol={
              {
                // span: 14,
              }
            }
            layout="horizontal"
            initialValues={{
              size: 'default',
            }}
            size={'default'}
            style={{
              maxWidth: 600,
            }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item label="新闻标题" name="title">
              <Input />
            </Form.Item>

            <Form.Item label="封面图片" name="imgurl">
              <Upload
                name="avatar"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                // action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                beforeUpload={beforeUpload}
                onChange={handleChange}
              >
                {imageUrl ? (
                  <img
                    src={imageUrl}
                    alt="avatar"
                    style={{
                      width: '100%',
                    }}
                  />
                ) : (
                  uploadButton
                )}
              </Upload>
            </Form.Item>

            <Form.Item label="发布时间" name="publish">
              <DatePicker showTime onChange={onChange} onOk={onOk} />
            </Form.Item>

            <Form.Item label="发布内容" name="content">
              <TextArea rows={18} maxLength={500} showCount allowClear />
            </Form.Item>
          </Form>
        </Card>
      </div>
    </div>
  );
}
